import time
import datetime
import binascii
import struct

def pack_date(dt):
    ''' Pack a date to an integer.
    
        The precision of microseconds is decreased so it fits under 65535.
    '''
    ret = struct.pack(">HBBBBBH", dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.microsecond / 100)
    return int(binascii.hexlify(ret), 16)
		
def unpack_date(l):
    ''' Unpack an integer to a date. '''
    string = hex(l)[2:].rstrip('L')
    
    # binascii requires an even length string
    if len(string) & 1:
        string = '0' + string
    string = binascii.unhexlify(string)
    
    if len(string) < 9: 
        raise ValueError("Error decoding date. Invalid packing.")

    vals = list(struct.unpack(">HBBBBBH", string))
    vals [6] *= 100
    return datetime.datetime(*vals)
